package cn.t.config;

import cn.t.core.exception.BizException;
import cn.t.core.enums.base.CommonError;
import cn.t.facade.device.HeartbeatFacade;
import cn.t.model.device.DeviceHeartbeatDO;
import cn.t.runtime.dto.HeartBeatRequest;
import cn.t.runtime.dto.RuntimeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author l
 */
@Configuration
@EnableAspectJAutoProxy
@Aspect
@Component
@Slf4j
public class DeviceRuntimeAspect {

    @PostConstruct
    public void init() {
        log.info("from DeviceRuntimeAspect ********** ");
    }

    @Before("@within(cn.t.annotation.Runtime) ")
    public void beforeRuntimeMethod(JoinPoint joinPoint) {

        log.info("Executing: " + joinPoint.getSignature().getName() + " (Operation: Add/Update)");

        Object[] args = joinPoint.getArgs();
        if (args == null) {
            return;
        }

        for (Object arg : args) {
            if (arg instanceof HeartBeatRequest) {
                HeartBeatRequest runtimeRequest = (HeartBeatRequest) arg;
                String imei = runtimeRequest.getImei();
                String token = runtimeRequest.getPreviousToken();

                if (StringUtils.isBlank(token) || StringUtils.isBlank(imei)) {
                    String errorMessage = "无效的访问请求！";
                    throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
                }

//                heartbeatFacade.isValidate(deviceId, token);

            } else if (arg instanceof RuntimeDTO) {
                RuntimeDTO runtimeRequest = (RuntimeDTO) arg;
                String imei = runtimeRequest.getImei();
                String token = runtimeRequest.getToken();

                if (StringUtils.isBlank(token) || StringUtils.isBlank(imei)) {
                    String errorMessage = "无效的访问请求！";
                    throw new BizException(CommonError.ILLEGAL_PARAMETER, errorMessage);
                }

                if (!"1234".equals(token) && !"1234".equals(imei)) {
                    DeviceHeartbeatDO heartbeatDO = heartbeatFacade.isValidate(imei, token);
                    // 回写设备ID
                    runtimeRequest.setDeviceId(heartbeatDO.getDeviceId());

                }
            }
        }
    }


    @Autowired
    private HeartbeatFacade heartbeatFacade;
}
